import React, { useState } from 'react'; // 导入React和useState
import { Tree, Button, Modal, Form, Input, Space, message, Popconfirm, Card } from 'antd'; // 导入Ant Design组件
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'; // 导入图标

// 模拟初始部门数据
const initialDepartments = [
  {
    title: '公司', // 部门名称
    key: '0', // 部门唯一key
    children: [
      {
        title: '技术部',
        key: '0-0',
        children: [
          { title: '前端组', key: '0-0-0' },
          { title: '后端组', key: '0-0-1' }
        ]
      },
      {
        title: '市场部',
        key: '0-1',
        children: []
      }
    ]
  }
];

const DepartmentManagement = () => {
  // 部门树数据
  const [departments, setDepartments] = useState(initialDepartments);
  // 当前选中的部门key
  const [selectedKey, setSelectedKey] = useState(null);
  // 控制模态框显示
  const [modalVisible, setModalVisible] = useState(false);
  // 当前操作类型 add/edit
  const [modalType, setModalType] = useState('add');
  // 表单实例
  const [form] = Form.useForm();

  // 选中树节点时触发
  const onSelect = (selectedKeys) => {
    setSelectedKey(selectedKeys[0]); // 设置当前选中key
  };

  // 打开新增部门模态框
  const handleAdd = () => {
    setModalType('add'); // 设置为新增
    form.resetFields(); // 重置表单
    setModalVisible(true); // 显示模态框
  };

  // 打开编辑部门模态框
  const handleEdit = () => {
    setModalType('edit'); // 设置为编辑
    // 获取当前选中部门名称
    const node = findNodeByKey(departments, selectedKey);
    form.setFieldsValue({ name: node ? node.title : '' }); // 设置表单初始值
    setModalVisible(true); // 显示模态框
  };

  // 删除部门
  const handleDelete = () => {
    if (!selectedKey) return;
    const newTree = deleteNodeByKey(departments, selectedKey);
    setDepartments(newTree);
    setSelectedKey(null);
    message.success('删除成功');
  };

  // 递归查找节点
  const findNodeByKey = (tree, key) => {
    for (let node of tree) {
      if (node.key === key) return node;
      if (node.children) {
        const found = findNodeByKey(node.children, key);
        if (found) return found;
      }
    }
    return null;
  };

  // 递归删除节点
  const deleteNodeByKey = (tree, key) => {
    return tree.filter(node => {
      if (node.key === key) return false;
      if (node.children) node.children = deleteNodeByKey(node.children, key);
      return true;
    });
  };

  // 递归更新节点
  const updateNodeByKey = (tree, key, newTitle) => {
    return tree.map(node => {
      if (node.key === key) {
        return { ...node, title: newTitle };
      }
      if (node.children) {
        return { ...node, children: updateNodeByKey(node.children, key, newTitle) };
      }
      return node;
    });
  };

  // 递归添加子节点
  const addChildNode = (tree, parentKey, newNode) => {
    return tree.map(node => {
      if (node.key === parentKey) {
        const children = node.children ? [...node.children, newNode] : [newNode];
        return { ...node, children };
      }
      if (node.children) {
        return { ...node, children: addChildNode(node.children, parentKey, newNode) };
      }
      return node;
    });
  };

  // 提交表单
  const handleOk = () => {
    form.validateFields().then(values => {
      if (modalType === 'add') {
        // 新增部门
        const newKey = Date.now().toString();
        const newNode = { title: values.name, key: newKey };
        if (selectedKey) {
          setDepartments(addChildNode(departments, selectedKey, newNode));
        } else {
          setDepartments([...departments, newNode]);
        }
        message.success('新增成功');
      } else if (modalType === 'edit') {
        // 编辑部门
        setDepartments(updateNodeByKey(departments, selectedKey, values.name));
        message.success('编辑成功');
      }
      setModalVisible(false);
      form.resetFields();
    });
  };

  return (
    <Card title="部门管理" bordered={false}> {/* 外层卡片 */}
      <Space style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增部门</Button>
        <Button icon={<EditOutlined />} disabled={!selectedKey} onClick={handleEdit}>编辑部门</Button>
        <Popconfirm title="确定删除该部门吗？" onConfirm={handleDelete} okText="确定" cancelText="取消">
          <Button icon={<DeleteOutlined />} danger disabled={!selectedKey}>删除部门</Button>
        </Popconfirm>
      </Space>
      <Tree
        treeData={departments}
        onSelect={onSelect}
        selectedKeys={selectedKey ? [selectedKey] : []}
        defaultExpandAll
      />
      <Modal
        title={modalType === 'add' ? '新增部门' : '编辑部门'}
        open={modalVisible}
        onOk={handleOk}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="部门名称" rules={[{ required: true, message: '请输入部门名称' }]}> 
            <Input placeholder="请输入部门名称" />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default DepartmentManagement; // 导出部门管理组件 